package com.example.myapplication.slice;

import com.example.myapplication.ResourceTable;
import com.example.myapplication.beans.*;
import com.example.myapplication.constant.Constant;
import com.example.myapplication.provider.ContactsProvider;
import com.example.myapplication.provider.IndexImgCarousel;
import com.example.myapplication.provider.TabPageSliderProvider;
import com.example.myapplication.utils.DataBaseUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;

import static ohos.data.search.schema.PhotoItem.TAG;

public class MainAbilitySlice extends AbilitySlice implements Component.FocusChangedListener {

//    private Gson gson = new Gson();
    private String userName;//存储token
//    private int status = 0;//用于判断用户信息的订单状态
//    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");//用于用户中心显示订单信息

    Context _this = this;

    //以下这些是联系人操作定义的常量
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.DEBUG, 0, TAG);

    private Image addContactsBtn; //添加联系人按钮
    private Image menuBtn; //菜单按钮
    private List<Contacts> list;    //列表数据源
    private ListContainer listContainer;   //list列表
    private ContactsProvider contactsProvider;    //list列表绑定的provider

    private TextField nameTf;     //联系人姓名输入框
    private RadioContainer genderRc;    //联系人性别单选框组合容器
    private TextField phoneTf;  //联系人电话号码输入框
    private RadioButton manRb;  //单选按钮，男
    private RadioButton ladyRb; //单选按钮，女

    private int currentIndex; //当前item的索引位，后边长按删除使用

    //定义系统自带的对话框相关的操作（联系人）
    private static final int DIALOG_BUTTON_CANCEL = 1;
    private static final int DIALOG_BUTTON_CONFIRM = 2;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);//设置默认加载页面，防止出现错误

        //将数据库操作封装到工具类中，在此方便引用
         userName = DataBaseUtil.getValue("userName",this);
        //System.out.println("-----------------" + token1);
        if (userName != null){//不为空，说明用户登陆过，加载首页
            //super.setUIContent(ResourceTable.Layout_ability_main);//将此行写到上边，以便用跳转方式（else里边）实现
            //1.初始化tabList
            TabList tabList = findComponentById(ResourceTable.Id_tab_list);
            String [] tabListTags = {"首页","分类","紧急联系人","我的"};
            for (int i = 0; i < tabListTags.length; i++) {
                TabList.Tab tab = tabList.new Tab(this);
                tab.setText(tabListTags[i]);
                tabList.addTab(tab);
            }

            //2.初始化PageSlider
            List<Integer> layoutFileIds = new ArrayList<>();
            layoutFileIds.add(ResourceTable.Layout_ability_main_index);
            layoutFileIds.add(ResourceTable.Layout_ability_main_category);
            layoutFileIds.add(ResourceTable.Layout_ability_main_contact);
            layoutFileIds.add(ResourceTable.Layout_ability_main_user_center);
            PageSlider pageSlider = findComponentById(ResourceTable.Id_page_slider);
            pageSlider.setSlidingPossible(false);
            pageSlider.setProvider(new TabPageSliderProvider(layoutFileIds,this));


            //3.TabList和PageSlider联动
            tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
                @Override
                public void onSelected(TabList.Tab tab) {
                    int index = tab.getPosition();//获取索引
                    pageSlider.setCurrentPage(index);//设置索引一致
                    if (index == 0){
                        //首页
                        initIndex(pageSlider);
                    }else if (index == 1){
                        //分类
                        initCategory(pageSlider);
                    }else if (index == 2){
                        //紧急联系人
                        initContact(pageSlider);
                    }else if (index == 3){
                        //我的
                        //以下两行用于设置接收传递的用户名信息
                        String userName = (String) intent.getParams().getParam("userName");
                        initUserCenter(pageSlider,userName);
                    }
                }

                @Override
                public void onUnselected(TabList.Tab tab) {}
                @Override
                public void onReselected(TabList.Tab tab) {}
            });

            //4.反向联动
            pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
                @Override
                public void onPageSliding(int i, float v, int i1) {}
                @Override
                public void onPageSlideStateChanged(int i) {}

                @Override
                public void onPageChosen(int i) {
                    //参数i表示当前pageSlider的索引
                    if (tabList.getSelectedTabIndex() != i){
                        tabList.selectTabAt(i);
                    }
                }
            });

            //5.TabList默认选中第一个菜单，并加载PageSlider的第一个页面（默认）
            tabList.selectTabAt(0);

            //登录成功的吐司弹窗
            ToastDialog toastDialog = new ToastDialog(this);
            toastDialog.setText("登录成功");
            toastDialog.setDuration(10000);
            toastDialog.setOffset(0,700);
            toastDialog.show();

        }else {//如果本地数据库没有用户数据（也就是没有登录过）则加载登录页面
            //也可用跳转方式实现
            //setUIContent(ResourceTable.Layout_ability_login);
            Intent i = new Intent();
            present(new LoginAbilitySlice(),i);
        }


    }

    //初始化方法
    //首页
    private void initIndex(PageSlider pageSlider) {
//        //服务器请求数据
//        try{
//            //一
//            //初始化首页轮播图
//            //放在一个线程中初始化
//            getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
//                //封装工具类，url服务器访问接口(此处调用木小果接口返回的图片)（自己更改）
//                String s = HttpRequestUtil.sendGetRequest(this,"https://api.muxiaoguo.cn/api/bing?api_key=9d48c99ba9825989&id=today&pn=8");
////            System.out.println("---------------------------------------------------------------");
////            System.out.println(s);
//                //将返回结果封装JavaBean
//                //然后解析
//                Gson gson = new Gson();
//                ResultVO resultVO = gson.fromJson(s,ResultVO.class);
//                //如果数据返回成功
//                if (resultVO.getCode() == 200){
//                    //将字符串对象转换成列表对象存入Javabean中
//                    String str = gson.toJson(resultVO.getData());
//                    List<IndexImage> list = gson.fromJson(str,new TypeToken<List<IndexImage>>(){}.getType());
//                    //组件的渲染只能放到UI线程中
//                    getUITaskDispatcher().asyncDispatch(() -> {
//                        //将轮播图数据渲染到以下类中
//                        IndexImgPageSliderProvider provider = new IndexImgPageSliderProvider(list,this);
//                        PageSlider indexImgPageSlider = findComponentById(ResourceTable.Id_index_image_pageSlider);
//                        indexImgPageSlider.setProvider(provider);
//                    });
//                }
//            });
//
//            //二
//            //获取推荐商品数据，显示到首页商品推荐中,即table组件布局中（创建线程访问接口）
//            TableLayout tableLayout = findComponentById(ResourceTable.Id_index_product_list_table);
//            getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
//                //（自己更改）将网络地址封装成常量，以便后期修改
//                String s = HttpRequestUtil.sendGetRequest(this, ApiUtil.BASE_PATH + "index/images");
//                Gson gson = new Gson();
//                ResultVO resultVO = gson.fromJson(s,ResultVO.class);
//                if (resultVO.getCode() == 200){
//                    //重新转换成json
//                    String dataStr = gson.toJson(resultVO.getData());
//                    List<Product> list = gson.fromJson(dataStr,new TypeToken<List<Product>>(){}.getType());
////                    //测试是否得到了返回结果
////                    for (Product product:list){
////                        System.out.println(product);
////                    }
//                    //将获取到的商品列表显示到table布局中
//                    getUITaskDispatcher().asyncDispatch(() -> {
//                        for (Product product:list){
//                            //1.获取table中显示每个商品的模板（product_list_item.xml)
//                            DirectionalLayout template = (DirectionalLayout) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_product_list_item_template,null,false);
//                            //2.将每个商品信息设置到模板的组件中
//                            Image image = template.findComponentById(ResourceTable.Id_product_item_image);
//                            Text text1 = template.findComponentById(ResourceTable.Id_product_item_name_text);
//                            Text text2 = template.findComponentById(ResourceTable.Id_product_item_price_text);
//
//                            //设置网络图片访问地址
//                            String imgUrl = ApiUtil.IMG_BASE_PATH + product.getImgs().get(0).getUrl(); //完整图片路径
//                            //工具类将网络图片加载到模板中
//                            LoadNetImageUtil.loadImg(this,imgUrl,image);
//                            text1.setText(product.getProductName());
//                            text1.setText(product.getSoldNum());
//
//                            //3.将完成数据渲染的模板添加到table模板中
//                            tableLayout.addComponent(template);
//
//                            //应将for循环添加到UI线程中
//
//                            //添加商品推荐信息的点击事件（如果有服务器，则需要把下面静态的点击事件删除）
//                            //并传递参数
//                            template.setClickedListener(component -> {
//                                Intent intent = new Intent();
//                                intent.setParam("productId",product.getProductId());
//                                present(new DetailAbilitySlice(),intent);
//                            });
//
//                        }
//                    });
//                }
//            });
//
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }



        //跳转搜索页面
        TextField searchTextField = findComponentById(ResourceTable.Id_index_search_textField);
        searchTextField.setFocusChangedListener(this);

        //轮播图
        getUITaskDispatcher().asyncDispatch(() -> {
            PageSlider carousel = findComponentById(ResourceTable.Id_index_image_pageSlider);

            List<IndexImg> list = new ArrayList<>();
            list.add(new IndexImg(ResourceTable.Media_heart9));
            list.add(new IndexImg(ResourceTable.Media_L2));
            list.add(new IndexImg(ResourceTable.Media_L1));
            list.add(new IndexImg(ResourceTable.Media_L4));

            IndexImgCarousel indexImgCarousel = new IndexImgCarousel(list,this);

        //导航点
        PageSliderIndicator indicator = findComponentById(ResourceTable.Id_indicator);
        ShapeElement normalElement = new ShapeElement();
        //未选中
        normalElement.setRgbColor(RgbColor.fromArgbInt(0xCCCCCC));
        normalElement.setAlpha(168);
        normalElement.setShape(ShapeElement.OVAL);
        normalElement.setBounds(0, 0, 20, 20);
        ShapeElement selectedElement = new ShapeElement();
        //选中
        selectedElement.setRgbColor(RgbColor.fromArgbInt(0x939393));
        selectedElement.setAlpha(168);
        selectedElement.setShape(ShapeElement.OVAL);
        selectedElement.setBounds(0, 0, 32, 32);
        indicator.setItemElement(normalElement, selectedElement);
        indicator.setItemOffset(60);
        indicator.setPageSlider(carousel);

            carousel.setProvider(indexImgCarousel);
        });


        //跳转到健康码页面
        DirectionalLayout healthCodeIcon = findComponentById(ResourceTable.Id_healthCodeIconLayout);
        healthCodeIcon.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                present(new HealthCode(),new Intent());
            }
        });
        //跳转到监测数据页面
        DirectionalLayout monitorDataLayout = findComponentById(ResourceTable.Id_monitor_data_layout);
        monitorDataLayout.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                present(new TodayMonitorDataSlice(),new Intent());
            }
        });

        //跳转商品详情页
        Component productLayout = pageSlider.findComponentById(ResourceTable.Id_layout_product1);
        productLayout.setClickedListener(component -> {
            Intent intent = new Intent();
            //intent.setParam("productId","1001");
            this.present(new DetailAbilitySlice(),intent);
        });
    }
    //分类
    private void initCategory(PageSlider pageSlider) {
        //跳转搜索页
        TextField searchTextField = findComponentById(ResourceTable.Id_category_search_textField);
        searchTextField.setFocusChangedListener(this);

        //参考下边将一级分类加入到集合中，然后遍历点击

        DirectionalLayout directionalLayout1 = findComponentById(ResourceTable.Id_first_category_direction1);
        Text firstCategoryText1 = directionalLayout1.findComponentById(ResourceTable.Id_first_category_text1);
        DirectionalLayout directionalLayout2 = findComponentById(ResourceTable.Id_first_category_direction2);
        Text firstCategoryText2 = directionalLayout2.findComponentById(ResourceTable.Id_first_category_text2);

        Text secondCategoryText1 = findComponentById(ResourceTable.Id_second_category_text1);
        Image image1 = findComponentById(ResourceTable.Id_third_category_image1);
        Image image2 = findComponentById(ResourceTable.Id_third_category_image2);
        Image image3 = findComponentById(ResourceTable.Id_third_category_image3);
        Text text1 = findComponentById(ResourceTable.Id_third_category_text1);
        Text text2 = findComponentById(ResourceTable.Id_third_category_text2);
        Text text3 = findComponentById(ResourceTable.Id_third_category_text3);
        Text secondCategoryText2 = findComponentById(ResourceTable.Id_second_category_text2);
        Image image11 = findComponentById(ResourceTable.Id_third_category_image11);
        Image image21 = findComponentById(ResourceTable.Id_third_category_image21);
        Image image31 = findComponentById(ResourceTable.Id_third_category_image31);
        Text text11 = findComponentById(ResourceTable.Id_third_category_text11);
        Text text21 = findComponentById(ResourceTable.Id_third_category_text21);
        Text text31 = findComponentById(ResourceTable.Id_third_category_text31);

        firstCategoryText1.setTextColor(new Color(Color.rgb(255,0x39,0x3b)));


        Component.ClickedListener listener= new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (component == directionalLayout1){
                    firstCategoryText1.setTextColor(new Color(Color.rgb(255,0x39,0x3b)));
                    firstCategoryText2.setTextColor(Color.BLACK);
                    secondCategoryText1.setText("便携式设备一");
                    image1.setPixelMap(ResourceTable.Media_watch);
                    image2.setPixelMap(ResourceTable.Media_hand);
                    image3.setPixelMap(ResourceTable.Media_earphone);
                    text1.setText("手表");
                    text2.setText("手环");
                    text3.setText("耳机");
                    secondCategoryText2.setText("便携式设备二");
                    image11.setPixelMap(ResourceTable.Media_watch);
                    image21.setPixelMap(ResourceTable.Media_hand);
                    image31.setPixelMap(ResourceTable.Media_earphone);
                    text11.setText("手表");
                    text21.setText("手环");
                    text31.setText("耳机");
                }else if (component == directionalLayout2){
                    firstCategoryText2.setTextColor(new Color(Color.rgb(255,0x39,0x3b)));
                    firstCategoryText1.setTextColor(Color.BLACK);
                    secondCategoryText1.setText("穿戴式设备一");
                    image1.setPixelMap(ResourceTable.Media_equipment1);
                    image2.setPixelMap(ResourceTable.Media_equipment2);
                    image3.setPixelMap(ResourceTable.Media_equipment3);
                    text1.setText("直立器");
                    text2.setText("足部矫形器");
                    text3.setText("腿部检测器");
                    secondCategoryText2.setText("穿戴式设备二");
                    image11.setPixelMap(ResourceTable.Media_equipment1);
                    image21.setPixelMap(ResourceTable.Media_equipment2);
                    image31.setPixelMap(ResourceTable.Media_equipment3);
                    text11.setText("直立器");
                    text21.setText("足部矫形器");
                    text31.setText("腿部检测器");
                }
            }
        };
        directionalLayout1.setClickedListener(listener);
        directionalLayout2.setClickedListener(listener);


    }
    //联系人
    private void initContact(PageSlider pageSlider) {
        getUITaskDispatcher().asyncDispatch(()->{
            initView();
            initListContainer();
        });


    }
        private void initView () {
            addContactsBtn = (Image) findComponentById(ResourceTable.Id_image_add);//添加联系人按钮
            menuBtn = (Image) findComponentById(ResourceTable.Id_image_menu);//菜单按钮
            Component.ClickedListener listenerContact = new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    switch (component.getId()) {
                        case ResourceTable.Id_image_add: //添加按钮
                            showAddContactsDialog();
                            break;
                        case ResourceTable.Id_image_menu: //菜单按钮
                            new ToastDialog(MainAbilitySlice.this).setText("菜单功能待完成").setDuration(2000).show();
                            break;

                    }
                }
            };
            addContactsBtn.setClickedListener(listenerContact);
            menuBtn.setClickedListener(listenerContact);
        }

        //创建并显示自定义的添加联系人操作的对话框
        private void showAddContactsDialog () {
            CommonDialog commonDialog = new CommonDialog(this);
            Component dialogComponent = LayoutScatter.getInstance(getContext())
                    .parse(ResourceTable.Layout_dialog_add_contacts, null, true);

//        commonDialog.setSize(800, 600);     //设置对话框尺寸
            Button btnConfirm = (Button) dialogComponent.findComponentById(ResourceTable.Id_btn_confirm);
            Button btnCancel = (Button) dialogComponent.findComponentById(ResourceTable.Id_btn_cancel);
            nameTf = (TextField) dialogComponent.findComponentById(ResourceTable.Id_tf_name);
            phoneTf = (TextField) dialogComponent.findComponentById(ResourceTable.Id_tf_phone);
            genderRc = (RadioContainer) dialogComponent.findComponentById(ResourceTable.Id_rc_gender);
            manRb = (RadioButton) dialogComponent.findComponentById(ResourceTable.Id_rb_man);
            ladyRb = (RadioButton) dialogComponent.findComponentById(ResourceTable.Id_rb_lady);
            manRb.setChecked(true);
            genderRc.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
                @Override
                public void onCheckedChanged(RadioContainer radioContainer, int i) {

                }
            });

            //采用传统的匿名内部类实现按钮监听器
            btnConfirm.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    new ToastDialog(_this).setText("确定").setDuration(2000).show();
                    //list.add(new Contacts("内马尔", 0));
                    Contacts contacts = generateContactsFromInput();
                    list.add(contacts);      //更新list中存储的数据
                    contactsProvider.notifyDataChanged();    //更新listcontainer
                    commonDialog.remove();
                }
            });
            //采用lamda表达式实现按钮监听器
            btnCancel.setClickedListener((Component component) -> {
                new ToastDialog(MainAbilitySlice.this).setText("取消").setDuration(2000).show();
                commonDialog.remove();
            });

            commonDialog.setContentCustomComponent(dialogComponent);
            commonDialog.show();
        }

        //通过对话框的输入页面输入的数据产生联系人
        private Contacts generateContactsFromInput () {
            Contacts contacts = new Contacts();
            HiLog.info(LABEL, "checked id =" + genderRc.getMarkedButtonId());
            if (genderRc.getMarkedButtonId() == Constant.GENDER_MAN) {
                contacts.setGender(Constant.GENDER_MAN);
            } else {
                contacts.setGender(Constant.GENDER_LADY);
            }
            contacts.setName(nameTf.getText().trim());
            contacts.setPhone(phoneTf.getText().trim());
            return contacts;
        }


        private void initListContainer () {
            listContainer = findComponentById(ResourceTable.Id_list_contacts);
            list = getData();//静态数据展示
            contactsProvider = new ContactsProvider(list, this);
            listContainer.setItemProvider(contactsProvider);

            //设置item的点击事件
            listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
                @Override
                public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                    // showToast("第"+i+"行被点击");  //通过吐司弹窗进行测试
                    //点击item之后跳转slice页面，并且传递数据
                    Intent intent = new Intent();
                    intent.setParam("contacts", list.get(i));
                    intent.setParam("name", list.get(i).getName());
                    present(new ContactsDetailSlice(), intent);
                }
            });

//            设置列表item的长按点击事件，弹出系统自带对话框，点击“确定”删除联系人
            listContainer.setItemLongClickedListener(new ListContainer.ItemLongClickedListener() {
                @Override
                public boolean onItemLongClicked(ListContainer listContainer, Component component, int i, long l) {
                    showToast("item" + i + "长按操作");
                    currentIndex = i;
                    CommonDialog commonDialog = new CommonDialog(MainAbilitySlice.this);
                    commonDialog.setSize(800, 200);
                    commonDialog.setCornerRadius(30);
                    commonDialog.setContentText("确认要紧急拨号给该联系人吗？");
                    commonDialog.setButton(DIALOG_BUTTON_CANCEL, "取消", clickedListener);
                    commonDialog.setButton(DIALOG_BUTTON_CONFIRM, "确定", clickedListener);
                    commonDialog.show();
                    return false;
                }
            });
        }
    private IDialog.ClickedListener clickedListener = new IDialog.ClickedListener() {
        @Override
        public void onClick(IDialog iDialog, int i) {
            switch (i) {
                case DIALOG_BUTTON_CANCEL:
//                    showToast("对话框取消");
                    iDialog.remove();
                    break;
                case DIALOG_BUTTON_CONFIRM:
//                    showToast("对话框确认");
//                    if (list != null && list.size() > currentIndex) {
////                        if (MyApplication.DEV_DATA_VERSION == MyApplication.SQLITE_DATA_VERSION) {
////                            contactsDao.deleteContacts(list.get(currentIndex).getId()); //从数据库删除联系人
////                        }
//                        list.remove(currentIndex);  //list数据源中删除该项联系人
//                        contactsProvider.notifyDataSetItemRemoved(currentIndex);  //刷新listcontainer显示
//                        iDialog.remove();           //删除这里有点小bug，可能是系统问题，这里必须还要在点一下手机页面listcontainer才能刷新显示
//                    }
                    present(new EmergencyPhone(),new Intent());
                    iDialog.remove();
                    break;
            }
        }
    };
//    定义系统自带的对话框相关的操作结束

        //用于列表点击事件的测试
        private void showToast (String msg){
            new ToastDialog(MainAbilitySlice.this).setText(msg).setDuration(2000).show();
        }

//        静态列表数据，在对接SQLite或者服务器端之后不再使用
        private List<Contacts> getData () {
            List<Contacts> list = new ArrayList<>();
            String[] names = {"小王", "小李", "帅帅", "小明", "羊羊", "小红", "小小", "小磊"};
            for (int i = 0; i <= 7; i++) {
                list.add(new Contacts(names[i], i));
            }
            return list;
        }



    //我的
    private void initUserCenter(PageSlider pageSlider,String userName) {

        String userName1 = DataBaseUtil.getValue("userName", this);
        Text userNameText = findComponentById(ResourceTable.Id_user_name_text);
        userNameText.setText(userName1);

        Button button = findComponentById(ResourceTable.Id_cancellation_button);
        button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                present(new LoginAbilitySlice(),new Intent());
            }
        });

    }



    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    //搜索框监听
    @Override
    public void onFocusChange(Component component, boolean b) {
        //当搜索框获得焦点时跳转
        if (b){
            present(new SearchAbilitySlice(),new Intent());
        }
    }

}
